# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd

from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt
import seaborn as sns


# %matplotlib inline

# path to where the data lies
#dpath = './data/'
data = pd.read_csv("../Bike-Sharing-Dataset/day.csv")
y = data['cnt'].values
X = data.drop('cnt', axis = 1)\
    .drop('dteday', axis = 1)\
    .drop('registered', axis = 1)\
    .drop('casual', axis = 1)\

#将数据分割训练数据与测试数据
from sklearn.model_selection import train_test_split

# 随机采样20%的数据构建测试样本，其余作为训练样本
X_train_raw, X_test_raw, y_train_raw, y_test_raw = train_test_split(X, y, random_state=33, test_size=0.2)

print(X_train_raw.head(1))
print(X_test_raw.head(1))
# print(y_train[0])

## data standard
from sklearn.preprocessing import StandardScaler

ss_X = StandardScaler()
ss_y = StandardScaler()

X_train = ss_X.fit_transform(X_train_raw)
X_test = ss_X.transform(X_test_raw)

y_train = ss_y.fit_transform(y_train_raw.reshape(-1, 1))
y_test = ss_y.transform(y_test_raw.reshape(-1, 1))

print("========= 数据标准化 =============")
print(X_train[0])
print(X_test[0])
print(y_train[0])
print(y_test[0])
# print(X_test.head(1))

print("========= 岭回归 =============")
from sklearn.linear_model import  RidgeCV

#设置超参数（正则参数）范围
alphas = [ 0.01 ,0.1, 1, 10 ]
#n_alphas = 20
#alphas = np.logspace(-5,2,n_alphas)

#生成一个RidgeCV实例
ridge = RidgeCV(alphas=alphas, store_cv_values=True)
#模型训练
ridge.fit(X_train, y_train)
#预测
y_test_pred_ridge = ridge.predict(X_test)
y_train_pred_ridge = ridge.predict(X_train)

print ('alpha is:', ridge.alpha_)
# 评估，使用r2_score评价模型在测试集和训练集上的性能
print 'The r2 score of RidgeCV on test is', r2_score(y_test, y_test_pred_ridge)
print 'The r2 score of RidgeCV on train is', r2_score(y_train, y_train_pred_ridge)

print("========= 拉锁回归 =============")
from sklearn.linear_model import LassoCV

#设置超参数搜索范围
alphas = [ 0.01, 0.1, 1, 10]

#生成一个LassoCV实例
lasso = LassoCV(alphas = alphas)

#训练（内含CV）
lasso.fit(X_train, y_train)

#测试
y_test_pred_lasso = lasso.predict(X_test)
y_train_pred_lasso = lasso.predict(X_train)

print ('alpha is:', lasso.alpha_)
# 评估，使用r2_score评价模型在测试集和训练集上的性能
print 'The r2 score of LassoCV on test is', r2_score(y_test, y_test_pred_lasso)
print 'The r2 score of LassoCV on train is', r2_score(y_train, y_train_pred_lasso)